package com.cxd.app.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cxd.app.entity.ReferrerInfo;
import com.cxd.app.entity.ReferrerPathInfo;
import com.cxd.app.entity.Referrers;
import com.cxd.app.entity.base.SourceReferrerBase;
import com.cxd.app.entity.base.TrusteeshipAccountBase;
import com.cxd.app.entity.base.UserActivityBase;
import com.cxd.app.entity.base.UserBase;
import com.cxd.app.service.BeanService;
import com.cxd.app.service.InvestService;
import com.cxd.app.service.LoanService;
import com.cxd.app.service.UserService;
import com.cxd.base.common.constants.Constants;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.controller.BaseController;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.MapUtil;

/**
 * @author wtj
 * @date 2015年12月1日 下午4:16:20
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */

@Controller("UserController")
@RequestMapping("userc")
public class UserController extends BaseController{
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	@Resource
	public BeanTools bt;
	
	@Resource
	public UserService userService;
	
	@Resource
	public InvestService investService;
	
	@Resource
	public BeanService beanService;
	
	@Resource
	public LoanService loanService;
	/**
	 * 登录操作
	 * @author wtj
	 *@param request
	 *@param response
	 *@param value
	 *@throws IOException
	 */
	@RequestMapping(value = "login", method = {RequestMethod.GET,RequestMethod.POST })
	public void login(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		JSONObject json = new JSONObject();
		try {
			userService.toLogin(json,value);
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, JSON.toJSONStringWithDateFormat(json, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
	}
	
	/**
	 * 用户注册
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "register", method = {RequestMethod.GET,RequestMethod.POST })
	public void register(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		System.out.println("注册:"+value);
		Map<String,String> param = MapUtil.jsonToMapString(value);
		String mobileNumber=param.get("phoneNo");//手机号,必填
		String username=param.get("userName");//用户名,必填
		String authCode=param.get("authCode");//验证码，必填
		String referrer=param.get("referrer");//推荐人
		String sourceCode = request.getHeader("sourceCode"); //官网code
		String sourceType = request.getHeader("sourceType"); //移动端统称  渠道终端类型  1:and 2:ios
		String useVersion = request.getHeader("useVersion");// 使用版本
		
		String logInfo = String.format("{phoneNo:%s,userName:%s,authCode:%s,referrer:%s,sourceCode:%s,sourceType:%s,useVersion:%s}", mobileNumber,username,authCode,referrer,sourceCode,sourceType,useVersion);
		super.requestLog("register",logInfo);
		JSONObject json = new JSONObject();
		try {
			userService.register(request,json,value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "用户注册成功");
			}
		} catch(CxdException e){
			json.put("result", new String[]{});
			super.cxdJsonException(json, e,logInfo);
		}catch (Exception e) {
			json.put("result", new String[]{});
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 判断手机是否已经被使用
	 */
	@RequestMapping(value = "isUsePhone", method = {RequestMethod.GET,RequestMethod.POST })
	public void isUsePhone(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("isUsePhone",value);
		JSONObject json = new JSONObject();
		try {
			Map<String,String> param = MapUtil.jsonToMapString(value);
			String phoneNo = param.get("phoneNo");
			if(StringUtils.isBlank(phoneNo)){
				param.put("isUse", Constants.FALSE_STR);
				json.put(Constants.RESULT, param);
				this.jsonMsg(json, 500, "参数异常");
			}else{
//				List<Map<String,Object>> listMap = bt.getListMap("USER", "MOBILE_NUMBER", phoneNo);
				List<Map<String,Object>> listMap = bt.queryListMap("SELECT * FROM USER WHERE MOBILE_NUMBER='"+phoneNo+"' or ID='"+phoneNo+"' ");
				if(listMap == null || listMap.size()==0){
					param.put("isUse", Constants.TRUE_STR);
					json.put(Constants.RESULT, param);
					this.jsonMsg(json, 200, "成功");
				}else{
					param.put("isUse", Constants.FALSE_STR);
					json.put(Constants.RESULT, param);
					this.jsonMsg(json, 500, "此号码已绑定其他账号");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 判断手机是否已经被使用
	 */
	@RequestMapping(value = "isHaveUser", method = {RequestMethod.GET,RequestMethod.POST })
	public void isHaveUser(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		JSONObject json = new JSONObject();
		try {
			Map<String,String> param = MapUtil.jsonToMapString(value);
			String phoneNo = param.get("phoneNo");
			if(StringUtils.isBlank(phoneNo)){
				param.put("isUse", Constants.FALSE_STR);
				json.put(Constants.RESULT, param);
				this.jsonMsg(json, 500, "参数异常");
			}else{
				List<Map<String,Object>> listMap = bt.queryListMap("SELECT * FROM USER WHERE MOBILE_NUMBER='"+phoneNo+"' or ID='"+phoneNo+"' ");
				if(listMap == null || listMap.size()==0){
					param.put("isUse", Constants.TRUE_STR);
					json.put(Constants.RESULT, param);
					this.jsonMsg(json, 200, "用户不存在");
				}else{
					param.put("isUse", Constants.FALSE_STR);
					json.put(Constants.RESULT, param);
					this.jsonMsg(json, 200, "用户已经存在");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	/**
	 * 注册发送验证码
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "registerSendVerificationCode", method = {RequestMethod.GET,RequestMethod.POST })
	public void registerSendVerificationCode(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("registerSendVerificationCode",value);
		JSONObject json = new JSONObject();
		try {
			Map<String,String> param = MapUtil.jsonToMapString(value);
			String phoneNo = param.get("phoneNo");
			if(StringUtils.isBlank(phoneNo)){
				throw new CxdException("手机不允许为空");
			}
			json = userService.verifyAuthInfo(json,phoneNo);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 获取用户个人信息
	 * @author wtj
	 * @date 2015年12月8日下午2:46:15
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @throws IOException
	 */
	@RequestMapping(value = "userInfo", method = {RequestMethod.GET,RequestMethod.POST })
	public void userInfo(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		JSONObject json = new JSONObject();
		try {
			if(!userService.checkToken(request)){
				this.jsonMsg(json, 403, "用户未登录");
			}else{
				userService.userInfo(json,value);
				if(json.get("status")==null){
					this.jsonMsg(json, 200, "成功");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, JSON.toJSONStringWithDateFormat(json, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
	}
	
	/**
	 * 用户名是否被使用
	 * @author wtj
	 * @date 2015年12月18日下午3:58:42
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "isUseUserName", method = {RequestMethod.GET,RequestMethod.POST })
	public void isUseUserName(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		JSONObject json = new JSONObject();
		try {
			userService.isUseUserName(json,value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	/**
	 * 根据渠道编号 获取渠道信息
	 * @param request
	 * @param response
	 * @param sourceCode
	 * @throws IOException
	 */
	@RequestMapping(value = "querySourceReferrer", method = {RequestMethod.GET,RequestMethod.POST })
	public void querySourceReferrer(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		JSONObject json = new JSONObject();
		try {
			Map<String,String> param = MapUtil.jsonToMapString(value);
			String sourceCode = param.get("sourceCode");
			if(StringUtils.isBlank(sourceCode)){
				this.jsonMsg(json, 500, "渠道编号不能为空");
			}else{
				if(StringUtils.isBlank(sourceCode)){
					sourceCode = "cc044b21bfba95aed0cfa42393db9dcf424e587b";
				}
				SourceReferrerBase srb = bt.queryBean("SOURCE_REFERRER", "SOURCE_CODE", sourceCode, SourceReferrerBase.class);
				json.put("SourceReferrer", srb);
				if(json.get("status")==null){
					this.jsonMsg(json, 200, "成功");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 判断用户是否是实名认证
	 * @author wtj
	 * @date 2015年12月8日下午7:10:47
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "isRealnameAuthentication", method = {RequestMethod.GET,RequestMethod.POST })
	public void isRealnameAuthentication(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("isRealnameAuthentication",value);
		JSONObject json = new JSONObject();
		try {
			if(!userService.checkToken(request)){
				this.jsonMsg(json, 403, "用户未登录");
			}else{
				Map<String,String> param = MapUtil.jsonToMapString(value);
				String userId = param.get("userId");
				if(StringUtils.isNotBlank(userId)){
					TrusteeshipAccountBase bean = bt.queryBean("TRUSTEESHIP_ACCOUNT", "ID", userId, TrusteeshipAccountBase.class);
					Map<String,Object> map = new HashMap<String,Object>();
						map.put("token",request.getHeader("TOKEN"));
					if (bean != null) {
						map.put("auth", "1"); // 已经认证
						UserBase userBase = beanService.getUserById(userId);
						map.put("realname", userBase.getRealname());
						map.put("idCard", userBase.getIdCard());
						map.put("mobileNumber", userBase.getMobileNumber());
					} else {
						map.put("auth", "0"); // 未认证
					}
					json.put("result", map);
					if(json.get("status")==null){
						this.jsonMsg(json, 200, "成功");
					}
				}else{
					this.jsonMsg(json, 500, "userId:不能为空");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 实名认证
	 * @author wtj
	 * @date 2015年12月8日下午6:46:06
	 * @param request
	 * @param response
	 * @param sourceCode
	 * @throws IOException
	 */
	@RequestMapping(value = "realnameAuthentication", method = {RequestMethod.GET,RequestMethod.POST })
	public void realnameAuthentication(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("realnameAuthentication",value);
		JSONObject json = new JSONObject();
		try {
			if(!userService.checkToken(request)){
				this.jsonMsg(json, 403, "用户未登录");
			}else{
				userService.realnameAuthentication(json,value);
			}
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 重置密码
	 * @author wtj
	 * @date 2015年12月8日下午7:11:45
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "resetPsw", method = {RequestMethod.GET,RequestMethod.POST })
	public void resetPsw(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("resetPsw",value);
		JSONObject json = new JSONObject();
		try {
			json = userService.resetPsw(json,value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "密码重置成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 重置易宝交易密码
	 * @author wtj
	 * @date 2015年12月23日下午10:45:15
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "resetYeePayPsw", method = {RequestMethod.GET,RequestMethod.POST })
	public void resetYeePayPsw(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("resetYeePayPsw",value);
		JSONObject json = new JSONObject();
		try {
			userService.resetYeePayPsw(json,value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 修改易宝手机号
	 * @author wtj
	 * @date 2015年12月26日下午10:45:15
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "resetYeePayMobile", method = {RequestMethod.GET,RequestMethod.POST })
	public void resetYeePayMobile(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("resetYeePayMobile",value);
		JSONObject json = new JSONObject();
		try {
			if(!userService.checkToken(request)){
				this.jsonMsg(json, 403, "用户未登录");
			}else{
				userService.resetYeePayMobile(json,value);
				if(json.get("status")==null){
					this.jsonMsg(json, 200, "成功");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 修改密码
	 * @author wtj
	 * @date 2015年12月23日下午9:59:43
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "updatePsw", method = {RequestMethod.GET,RequestMethod.POST })
	public void updatePsw(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("updatePsw",value);
		JSONObject json = new JSONObject();
		try {
			if(!userService.checkToken(request)){
				this.jsonMsg(json, 403, "用户未登录");
			}else{
				json = userService.updatePsw(json,value);
				if(json.get("status")==null){
					this.jsonMsg(json, 200, "密码修改成功");
				}
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 线下见面会活动申请
	 * @param mobile
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "meeting_apply", method = {RequestMethod.POST,RequestMethod.GET })
	public void activityApply(@RequestParam String mobile,HttpServletRequest request,HttpServletResponse response)throws IOException {
		String status1 = "报名成功，工作人员将在3个工作日内联系您";
		String status2 = "您的月标待回款低于5万元，不符合报名条件，快去投资吧";
		String status3 = "您已经参加过往届见面会，不符合报名条件，详见参会须知";
		String status4 = "正在审核中";
		boolean isTrue = false;
		JSONObject json = new JSONObject();
		try {
			UserBase user = userService.getUserByMobile(mobile);
			if(user == null){
				json.put("success", false);
				json.put("msg", "号码不存在，请重新输入");
				super.responseSendMsg(request,response, json);
				isTrue = true;
			}
			
			// 报名时用户投资非八天标待回款金额
			Double investMoney = userService.getUserSumInvestNo8Day(user.getId());
			UserActivityBase userAct = userService.getActivityApplyOldByMobile(mobile);
			if(userAct!=null && !isTrue){
				userService.saveActivityApply(mobile,user,investMoney,"3");
				json.put("success", false);
				json.put("msg", status3);
				super.responseSendMsg(request,response, json);
				isTrue = true;
			}
			
			userAct = userService.getActivityApplyNowByMobile(mobile);
			if(userAct!=null && !isTrue){
				json.put("success", false);
				if(userAct.getStatus().equals("1")){
					json.put("msg", status1);
				}else if(userAct.getStatus().equals("2")){
					json.put("msg", status2);
				}else if(userAct.getStatus().equals("3")){
					json.put("msg", status3);
				}else if(userAct.getStatus().equals("4")){
					json.put("msg", status4);
				}
				super.responseSendMsg(request,response, json);
				isTrue = true;
			}
			
			if((investMoney==null || investMoney<50000) &&  !isTrue){
				userService.saveActivityApply(mobile,user,investMoney,"2");
				json.put("success", false);
				json.put("msg", status2);
				super.responseSendMsg(request,response, json);
				isTrue = true;
			}
			
			if(!isTrue){
				userService.saveActivityApply(mobile,user,investMoney,"1");
				json.put("success", "true");
				json.put("msg", status1);
			}
			super.responseSendMsg(request,response, json);
		} catch (Exception e) {
			super.jsonException(json, e, logger);
		}
	}
	
	/**
	 * 获取推荐人详细列表
	 * @author weiqingfeng
	 * @param userId,用户ID
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "getReferrerInfoList", method = {RequestMethod.GET, RequestMethod.POST})
	public void getReferrerList(String value, HttpServletRequest request, HttpServletResponse response){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		//获取被推荐人List
		List<UserBase> userInfoList = userService.getReferrerListByUserId(userId);
		
		Referrers referrers = new Referrers();
		List<ReferrerInfo> infoList = new ArrayList<ReferrerInfo>();
		//判断每个用户是否投资过
		for(UserBase user : userInfoList){
			ReferrerInfo reInfo = new ReferrerInfo();
			reInfo.setRegTime(user.getRegisterTime());
			reInfo.setMoblieNumber(user.getMobileNumber());
			if(investService.userIsInvest(user.getId())){
				reInfo.setStatus("1");
			}else{
				reInfo.setStatus("0");
			}
			infoList.add(reInfo);
		}
		ReferrerPathInfo re = new ReferrerPathInfo();
		//h5推广页
		re.setSharePath("http://m2.51cxd.com/reg3");
		//banner页
		re.setBannerPah("http://www.51cxd.com/activities/0530/invest_wap/tpl/six_year/six/invite_june.html");
		//title
		re.setTitle("推广");
		//分享描述
		re.setContents("诚信贷，让您的财富每年增值20%！投资越多奖励越多，300元红包等你来拿！");
		referrers.setReInfos(infoList);
		referrers.setrPathInfo(re);
		JSONObject json = new JSONObject();
		try {
			json.put("result", referrers);
			json.put("status", "200");
			json.put("msg", "SUCCESS");
			super.responseSendMsg(response, json);
		} catch (IOException e) {
			e.printStackTrace();
			json.put("status", "404");
			json.put("msg", "获取推荐人信息失败");
		}
	}
	
	/**
	 * 获取用户投资回款日历
	 * @author wtj
	 * @date 2016年5月11日下午3:44:36
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "loanInvestBackCalendar", method = {RequestMethod.GET,RequestMethod.POST })
	public void loanInvestBackCalendar(HttpServletRequest request,HttpServletResponse response,String value)throws IOException {
		super.requestLog("loanInvestBackCalendar",value);
		JSONObject json = new JSONObject();
		try {
			userService.loanInvestBackCalendar(json,value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "获取数据成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(response, json);
	}
	
	/**
	 * 获取某天回款记录
	 * @author wtj
	 * @date 2016年5月11日下午5:07:07
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "backDateOfInvest", method = {RequestMethod.GET,RequestMethod.POST })
	public void backDateOfInvest(HttpServletRequest request,HttpServletResponse response,String value)throws IOException{
		super.requestLog("backDateOfInvest",value);
		Long beginTime = System.currentTimeMillis();
		JSONObject json = new JSONObject();
		try {
			loanService.backDateOfInvest(json, value);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,value);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(beginTime,response, JSON.toJSONStringWithDateFormat(json, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
	} 
}
